package com.ruoyi.asset.common;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import java.sql.*;

/**
 * @author jiangxiangjin
 * @version V1.0.0
 * @description
 * @date 2023/4/11 17:08
 */
@Configuration
public class SQLServerConfig {
    //加载驱动
    @Value("${SQLServer.driver}")
    private String driver;
    //获取用户名
    @Value("${SQLServer.user}")
    private String user;
    //获取密码
    @Value("${SQLServer.password}")
    private String password;
    //获取本地数据库
    @Value("${SQLServer.url}")
    private String url;

    public Connection conn=null;
    public PreparedStatement ps=null;
    public ResultSet rs=null;

    public Connection getConnection(){
        if (conn==null) {
            try {
                Class.forName(driver);
                //连接数据库
                conn= DriverManager.getConnection(url, user, password);
                System.out.println("数据库连接成功");
            } catch (Exception e) {
                System.out.println("获取数据库连接对象时产生的异常"+e);
            }
        }
        return conn;
    }
    //关闭数据库连接
    public void closeAll(Connection conn,Statement stmt,ResultSet rs,PreparedStatement pst){
        if (rs!=null) {
            try {
                rs.close();
                System.out.println("关闭数据库连接");
            } catch (Exception e) {
                System.out.println("关闭数据连接时产生的异常"+e);
            }
        }
        if (stmt!=null) {
            try {
                stmt.close();
                System.out.println("关闭数据库连接");
            } catch (Exception e) {
                System.out.println("Statement对象关闭数据库的异常"+e);
            }
        }
        if (pst!=null) {
            try {
                pst.close();
                System.out.println("关闭数据库连接");
            } catch (SQLException e) {
                e.printStackTrace();
                System.out.println("PreparedStatement对象关闭数据库的异常"+e);
            }
        }
        if (conn!=null) {
            try {
                conn.close();
                System.out.println("关闭数据库连接");
            } catch (Exception e) {
                System.out.println("数据库连接对象的异常"+e);
            }
        }
    }
}
